<template>
  <div class="hawkContent">
    <!-- 面包屑 -->
    <hawk-breadcrumb></hawk-breadcrumb>
    <!-- 搜索、添加区域 -->
    <el-row :gutter="20" style="padding-left: 20px;">
      <el-col :span="6" style="display:flex;align-items: center">
        <span style="width:100px; color: #666666; font-size: 13px">告警组名称：</span>
        <el-input placeholder="请输入告警组名称" v-model="queryForm.query.name">
        </el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="hawkSearch" @click="search">搜索</el-button>
        <el-button plain @click="reSet">重置</el-button>
      </el-col>
      <el-col :span="4"
              style="float: right;text-align: right;padding-right: 30px">
        <el-button type="hawkCreate" @click="edit">创建告警组</el-button>
      </el-col>
    </el-row>
    <!-- 引入表格组件(告警分组表) -->
    <hawk-table v-model="multipleSelection" :page="queryForm.page"
                :table-data="tableData" :number="true" :options="[
        { key: 'name', label: '告警组名称' },
        { key: 'handle', label: '操作' }
      ]">
      <template #handle="{ row }">
        <span class="hawk-text-btn" @click="edit(row)">编 辑</span>
        <span class="hawk-text-divider">|</span>
        <span class="hawk-text-btn" @click="del(row)">删 除</span>
        <!-- <span class="hawk-text-divider">|</span>
        <span class="hawk-text-btn" @click="details(row)">详情</span> -->
      </template>
    </hawk-table>
    <!-- 表格底部 -->
    <div class="bottom-btns">
      <div class="bottom-btns-left">
        <div class="bottom-btns-left-num">
          {{ multipleSelection.length }} 选择
        </div>
        <el-button type="hawkDelete" @click="catchDelete()">批量删除</el-button>
      </div>
      <!-- 分页 -->
      <el-pagination background @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page.sync="queryForm.page.current"
                     :page-sizes="[10, 20, 50, 100]"
                     :page-size="queryForm.page.size"
                     layout=" prev, pager, next,sizes" :total="total">
      </el-pagination>
    </div>
    <!-- 添加和修改模态框 -->
    <el-dialog :title="formTitle" :visible.sync="addDialogVisible"
               :close-on-click-modal="false" @close="addDialogClosed">
      <!-- 内容主题区 -->
      <el-form label-position="top" :model="addForm" :rules="addFormRules"
               ref="addFormRef" label-width="120px">
        <el-form-item label="告警组名称" prop="name"
                      style="width:100%;margin-right:0">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>

        <el-form-item label="选择用户" prop="userIds" v-show="addForm.id"
                      style="width:100%;margin-right:0">

          <el-select v-model="addForm.userIds" multiple filterable 
                     default-first-option placeholder="请选择用户">
            <!-- 添加用户的框 -->
            <el-option v-for="item in sysUsers" :key="item.id"
                       :label="item.nickName" :value="item.id">
            </el-option>

          </el-select>

        </el-form-item>

      </el-form>
      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
/**
 * @author 秦秋雅
 * @description 告警分组列表的视图层
 * @api /monitor/config/group
 * @since 2021年11月08日 13:50
 * @update 2021年11月08日 14:10
 * @modifier 秦秋雅
 * @bug 无
 * @version v1.0.0
 */
import { getGroupUser, getAllUser, getList, doDelete, doAdd, doEdit, getDetail } from '@/api/monitor/config/group'
export default {
  data () {

    let inHaveName = (rule, value, callback) => {


      let find = this.tableData.find(el => {
        return el.name == value
      })
      if (find) {
        callback(new Error('名称已经存在'))
      } else {
        callback()
      }

    }

    return {
      /**
       * 所有用户
       */
      sysUsers: [],

      /**
       * 已经选择的用户
       */
      selectedUser: [],


      // 多选
      multipleSelection: [],
      // 模态框
      addDialogVisible: false,
      // 模态框标题
      formTitle: '添加告警组',
      // 查询条件
      queryForm: {
        query: {
          name: ''
        },
        page: {
          current: 1,
          size: 10
        }
      },
      // 数据总量（条数）
      total: 0,
      // 表格数据
      tableData: [],
      // 添加表单条件
      addForm: {
        name: '',
        id: '',
        userIds: []
      },
      // 表单验证
      addFormRules: {
        name: [
          { required: true, message: '请输入告警组名称', trigger: 'blur' },
          {
            min: 2,
            max: 20,
            message: '告警组名称的长度在2-20个字符之间',
            trigger: 'blur'
          },
          { validator: inHaveName, trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.init()

    // 获得所有用户
    getAllUser()
      .then(ret => {
        console.log(ret);
        if (ret.code == 20000) {
          this.sysUsers = ret.data
        }
      })

  },
  // 方法集合
  methods: {
    // 搜索
    async search () {
      // 判断搜索信息是否为空
      if (this.queryForm.query.name == '') {
        this.$message({
          type: 'warning',
          message: '请输入搜索信息！'
        })
        return
      }
      this.queryForm.page.current = 1
      this.multipleSelection = []
      this.init()
    },
    // 重置搜索信息
    reSet () {
      this.queryForm = this.$options.data().queryForm
      this.init()
    },
    // 获取列表
    async init () {
      const ret = await getList(this.queryForm)
      console.log(ret);

      this.tableData = ret.data.records
      this.total = ret.data.total
    },
    // 每页数量修改
    handleSizeChange (val) {
      this.queryForm.page.size = val
      this.init()
    },
    // 页码跳转
    handleCurrentChange (val) {
      this.queryForm.page.current = val
      this.init()
    },
    // 批量删除
    catchDelete () {
      let list = []
      this.multipleSelection.forEach(item => {
        list.push(item.id)
      })
      this.$confirm('此操作将删除该所选数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(async () => {
          let ret = await doDelete(list)
          
           if (ret.code == 20000) {

            let type = ''
            if (ret.data) {
              ret.message = '删除成功'
              type = 'success'
            } else {
              type = 'error'
            }

            this.$message({
              type: type,
              message: ret.message,
            })

            // console.log(this.multipleSelection.length);
            if (this.multipleSelection.length == this.tableData.length) {
              this.queryForm.page.current = this.queryForm.page.current - 1
              if (this.queryForm.page.current < 1) {
                this.queryForm.page.current = 1
              }
            }

            this.multipleSelection = []
            console.log('-------------init---');
            this.init()

          }
        })
        .catch(() => {
          this.$message.info('已取消删除')
          this.$refs.multipleTable.clearSelection()
        })
    },
    // 添加、编辑方法
    async edit (row) {
      if (!row.id) {
        this.formTitle = '添加告警组'
      } else {
        this.formTitle = '修改告警组'
        Object.assign(this.addForm, row)

        let ret = await getGroupUser(row.id)
        console.log(ret);
        if (ret.code == 20000) {
          this.selectedUser = ret.data
          // 将选中的ID 添加至 
          this.addForm.userIds = []
          this.selectedUser.forEach(ele => {
            this.addForm.userIds.push(ele.id)
          })
        }
        console.log(this.addForm);
      }
      // 显示编辑框时，获得当前分组的用户
      this.addDialogVisible = true
    },

    // 模态框状态
    addDialogClosed () {
      this.addForm = this.$options.data().addForm
      // 模态框关闭时重新请求数据
      console.log(this.addForm);
      this.init()
      this.addDialogVisible = false
      this.$refs.addFormRef.resetFields()
    },
    // 执行添加和编辑
    save () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        if (this.addForm.id) {
          let ret = await doEdit(this.addForm)
          console.log(ret);
          if (ret.code == 20000) {

            this.$msg.success(ret.message)
            this.multipleSelection = []
          }
        } else {
          let ret = await doAdd(this.addForm)
          console.log(ret);
          if (ret.code == 20000) {

            this.$msg.success(ret.message)
            this.multipleSelection = []
          }
        }
        this.addDialogClosed()
      })
    },
    // 删除
    del (row) {
      this.$confirm(`此操作将删除${row.name}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(async () => {
          let ret = await doDelete([row.id])
          console.log(ret);
          if (ret.code == 20000) {

            let type = ''
            if (ret.data) {
              ret.message = '删除成功'
              type = 'success'
            } else {
              type = 'error'
            }

            this.$message({
              type: type,
              message: ret.message,
            })

            // console.log(this.multipleSelection.length);
            if (this.tableData.length == 1) {
              this.queryForm.page.current = this.queryForm.page.current - 1
              if (this.queryForm.page.current < 1) {
                this.queryForm.page.current = 1
              }
            }

            this.multipleSelection = []
            console.log('-------------init---');
            this.init()

          }
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    async details (row) {
      console.log(row);

      let ret = await getDetail(row.id)
      console.log(ret);

    }
  }
}
</script>
<style lang="scss" scoped></style>
